package com.eerl.pdev.terminal.cmd;

import com.eerl.pdev.util.EToolPluginConsoleToolWindowFactory;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.util.Alarm;

public class TerminalTimer implements Disposable, Runnable {

    private final Alarm alarm;
    private Terminal instance;

    private Project project;

    public TerminalTimer(Project project) {
        this.project = project;
        alarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, this);
    }

    public void startTimer(Terminal instance) {
        this.instance = instance;
        alarm.addRequest(this, instance.getSShAliveCheckTime());
    }

    @Override
    public void dispose() {
        alarm.cancelAllRequests();
    }

    @Override
    public void run() {
        EToolPluginConsoleToolWindowFactory.debugPrint(
            project,
            String.format(
                "now start timer, check time: %d | connect: %d | lastExecTime: %d",
                instance.getSShMaxAliveTimeoutMs(),
                instance.getSShAliveCheckTime(),
                instance.getLastExecCommandUnixtime()
            )
        );
        long diffMs = System.currentTimeMillis() - instance.getLastExecCommandUnixtime();
        if (diffMs > instance.getSShMaxAliveTimeoutMs()) {
            // 超时
            instance.close();
        } else {
            instance.timeUpdate();
            alarm.addRequest(this, instance.getSShAliveCheckTime());
        }
    }
}
